package com.yict.csms.baseInfo.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yict.common.entity.PageEntity;
import com.yict.common.service.impl.CommonService;
import com.yict.csms.baseInfo.dao.impl.ContractTypeDaoImpl;
import com.yict.csms.baseInfo.entity.ContractType;
import com.yict.csms.baseInfo.service.IContractTypeService;
import com.yict.csms.company.entity.Company;
import com.yict.csms.system.entity.Wharf;

/**
 * 
 * 
 * @author Patrick.Deng
 * 
 */
@Service
public class ContractTypeServiceImpl extends CommonService<ContractType, Long>
		implements IContractTypeService {
	@Autowired
	private ContractTypeDaoImpl contractTypeDao;

	public List<ContractType> search(Map<String, Object> queryMap,
			PageEntity page) {
		StringBuilder queryString = new StringBuilder();
		pageEntity = new PageEntity();
		queryString.append("from ContractType as c where 1=1");
		if (queryMap != null && queryMap.size() > 0) {
			String typeCode = (String) queryMap.remove("typeCode");
			if (typeCode != null && !"".equals(typeCode)) {
				queryMap.put("typeCode", "%" + typeCode.toLowerCase() + "%");
				queryString.append(" and lower(c.typeCode) like :typeCode");
			}
			if (queryMap.get("typeName") != null && !"".equals(queryMap.get("typeName"))) {
				queryMap.put("typeName", queryMap.get("typeName").toString().toLowerCase());
				queryString.append(" and lower(c.typeName) like :typeName");
			}
		}
		String field = " order by c.createDate desc";
		if (page.getField() != null&&!"".equals(page.getField()) &&page.getOrder()!= null && !"".equals(page.getOrder())) {
			field = " order by c." + page.getField() + page.getOrder();
		}
		queryString.append(field);
		List<ContractType> list = contractTypeDao.search(queryString.toString(), queryMap, page);
		pageEntity.setTotalRecord(contractTypeDao.getPageEntity().getTotalRecord());
		return list;
	}
	
	/**
	 * 根据承包商过滤
	 * @param companyid
	 * @return
	 */
	public List<ContractType> listByCompany(Long companyid,Date cntDate){
		String hql = "select t from ContractType t left join t.contractSet c left join c.contractRateSet r " +
				"where c.company.companyId = :companyid and r.ratestutas=:ratestutas " +
				"and r.effectiveDate <= :cntDate and r.expirationDate >= :cntDate";
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("companyid", companyid);
		map.put("cntDate", cntDate);
		map.put("ratestutas", "Y");
		List<ContractType> list;
		try {
			list = contractTypeDao.search(hql,map, null);
		} catch (Exception e) {
			list = new ArrayList<ContractType>();
		}
		return list;
	}
	
	/**
	 * 根据id查找实体
	 * @param ids
	 * @return
	 */
	public List<ContractType> listByIds(Collection<Long> ids){
		if(ids == null || ids.size() == 0) return new ArrayList<ContractType>();
		String hql = "from ContractType t where typeId in (:ids)";
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("ids", ids);
		List<ContractType> list;
		try {
			list = contractTypeDao.search(hql,map, null);
		} catch (Exception e) {
			list = new ArrayList<ContractType>();
		}
		return list;
	}

	public boolean verifyContract(Long typeId) {
		return contractTypeDao.verifyContract(typeId);
	}

	public LinkedHashMap<String, String> getContractTypeSelectMap() {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		List<ContractType> list = contractTypeDao.getContractTypeSelectMap();
		for (ContractType contractType : list) {
			map.put(contractType.getTypeId().toString(),contractType.getTypeName());
		}
		return map;
	}
	
	public LinkedHashMap<String, String> getWharfSelectMap() {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		List<Wharf> list = contractTypeDao.getWharfSelectMap();
		for (Wharf wharf : list) {
			map.put(wharf.getWharfId().toString(), wharf.getWharfName());
		}
		return map;
	}
	
	public ContractType findById(Long id) {
		return contractTypeDao.findById(id);
	}

	@Override
	@Transactional(readOnly = false)
	public boolean save(ContractType t) throws Exception {
//		Map<String,Object> map = new HashMap<String, Object>();
//		map.put("typeCode", t.getTypeCode());
//		List<ContractType> list = contractTypeDao.list(map, null, 0, 0);
//		if(list.size() > 0) throw new Exception("已经存在相同的代码");
		return super.save(t);
	}

	@Override
	@Transactional(readOnly = false)
	public boolean update(ContractType t) throws Exception {
//		Map<String,Object> map = new HashMap<String, Object>();
//		map.put("typeCode", t.getTypeCode());
//		List<ContractType> list = contractTypeDao.list(map, null, 0, 0);
		ContractType vo;
//		if(list.size() > 0){
//			vo = list.get(0);
//			if(!vo.getTypeId().equals(t.getTypeId())) 
//				throw new Exception("已经存在相同的代码");
//		}else{
			vo = contractTypeDao.findById(t.getTypeId());
//		}
			if(vo == null) {
				return false;
			}
		vo.setTypeCode(t.getTypeCode());
		vo.setTypeName(t.getTypeName());
		vo.setUpdateDate(t.getUpdateDate());
		vo.setUpdatePerson(t.getUpdatePerson());
		return true;
//		return super.update(t);
	}

	/**
	 * 代码、合同类别是否存在
	 * @param contractType
	 * @param isSave
	 * @return true - 存在
	 */
	public boolean check(ContractType contractType, boolean isSave) {
		StringBuilder queryString = new StringBuilder();
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryString.append("from ContractType as c where 1=1 and ( lower(c.typeCode) =:typeCode or lower(c.typeName) =:typeName )");
		queryMap.put("typeCode", contractType.getTypeCode()== null?null:contractType.getTypeCode().toLowerCase());
		queryMap.put("typeName", contractType.getTypeName()== null?null:contractType.getTypeName().toLowerCase());
		
		if(isSave) {
			queryString.append(" order by c.createPerson");
		} else {
			queryString.append(" and c.typeId not in (:typeId) order by c.createPerson");
			queryMap.put("typeId", contractType.getTypeId());
		}
		List<ContractType> list =  contractTypeDao.search(queryString.toString(),queryMap,null);
		if (list == null || list.size() <= 0) {
			return false;
		}
		return true;
	}
	
	/**
	 * 根据属性查找唯一记录
	 * @param value
	 * @param propertyName
	 * @return
	 * @throws Exception
	 */
	public ContractType findByUnique(Object value,String propertyName) {
		ContractType vo = null;
		Map<String,Object> map = new HashMap<String, Object>();
		map.put(propertyName, value);
		List<ContractType> list = contractTypeDao.list(map, null, 0, 0);
		if(list.size() > 1) 
			throw new RuntimeException("与期望的唯一记录不一致，找到多个记录:" + propertyName + "=" + value);
		if(list.size() == 1) vo = list.get(0);
		return vo;
	}
}
